// compontnts/input/lt-input.js
import {formVerify} from "../../../utils/util"
import {getDictInfo} from "../../../api/dict"
const defaultSettings = require('../../../config/defaultSettings')
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    formData:{
      type:Object,
      value:{}
    },
    field:{
      type:Object,
      value:{}
    },
    betweenSign:{
      type:String,
      value:""
    },
   
  },
  lifetimes: {
    created:function(){
      
    },
    attached: async function() {
      // 在组件实例进入页面节点树时执行,初始化一些操作
      if(this.data.field['clean']){
        this.setData({cancelButtonText:'清空'})
      }
      await this.initDictData()
    },
    detached: function() {
      // 在组件实例被从页面节点树移除时执行
    },
  },
  observers:{
    'dictOptions':function(dictOptions){
      let tempTextColumns=[]
      let tempValueMap=new Map()
      let tempTextMap = new Map()
      for(var item of dictOptions){
        tempTextColumns.push(item.itemText)
        tempValueMap.set(item.itemText,item.itemValue)
        tempTextMap.set(item.itemValue,item.itemText)
      }
 
      this.setData({textColumns:tempTextColumns,valueMap:tempValueMap})
      if(this.data.formData[this.data.field['field']+this.data.betweenSign]){
        let initValueArr = this.data.formData[this.data.field['field']+this.data.betweenSign].split(",")
        let initTextArr = []
        for(var val of initValueArr){
          if(tempTextMap.get(val)){
            initTextArr.push(tempTextMap.get(val))
          }
        }
        this.setData({value:initTextArr})
      }
    },
    'formData':function(formData){
      if(formData[this.data.field['field']+this.data.betweenSign]){
        let initValueArr = formData[this.data.field['field']+this.data.betweenSign].split(",")
        let initTextArr = []
        for(var val of initValueArr){
          if(tempTextMap.get(val)){
            initTextArr.push(tempTextMap.get(val))
          }
        }
        this.setData({value:initTextArr})
      }else{
        this.setData({value:""})
      }
    }
  },
  /**
   * 组件的初始数据
   */
  data: {
    errorMessage:"",
    isShow:false,
    valueMap: new Map(),
    textColumns:[],
    dictOptions: [],
    resultOptions:[],
    value:[],
    text:[],
    cancelButtonText:'取消',
    primaryColor:defaultSettings.primaryColor,
  },
 
  /**
   * 组件的方法列表
   */
  methods: {
    async initDictData(){
      if(this.data.field["options"] && this.data.field["options"].length>0){
        this.setData({dictOptions:this.data.field["options"]})
        return
      }
      if(!this.data.field['dictCode']){
        return
      }

      let that = this
      if(getApp().globalData.dictInfo[that.data.field['dictCode']]){
        this.setData({dictOptions:Object.assign([],getApp().globalData.dictInfo[that.data.field['dictCode']])})
        return
      }
      await getDictInfo(this.data.field['dictCode'],this.data.field['dictParam'] || '').then(res=>{
        if(res.success){
          that.data.resultOptions=[]
          if(that.data.field['replaceFields']){
            for(var val of res.result[that.data.field['dictCode']]){
              let replaceObj={};
              if(that.data.field.replaceFields['itemFilter']){
                  replaceObj['itemFilter'] = val[that.data.field['replaceFields']['itemFilter']]
              }else{
                  replaceObj['itemFilter'] = val['itemFilter']
              }
              if(that.data.field['replaceFields']['itemText']){
                  replaceObj['itemText'] = val[that.data.field['replaceFields']['itemText']]
              }else{
                  replaceObj['itemText'] = val['itemText']
              }
              if(that.data.field['replaceFields']['itemValue']){
                  replaceObj['itemValue'] = val[that.data.field['replaceFields']['itemValue']]
              }else{
                  replaceObj['itemValue'] = val['itemValue'] 
              }
              that.data.resultOptions.push(replaceObj);
            }
          }else{
            that.data.resultOptions = res.result[that.data.field['dictCode']]
          }
          this.setData({dictOptions:Object.assign([],that.data.resultOptions)})
          getApp().globalData.dictInfo[that.data.field['dictCode']] = that.data.resultOptions
          
        }else{
          wx.showToast({
            icon:"error",
            title: res.message,
          })
        }
      })
    },
    toggle(event) {
      const { index } = event.currentTarget.dataset;
      const checkbox = this.selectComponent(`.checkboxes-${index}`);
      checkbox.toggle();
    },
    onChange(event) {
      this.setData({value: event.detail});
      //将输入框改变的值实时赋值给formData
      let tempVal=''
      if(this.data.value.length>0){
        for(var val of this.data.value){
          tempVal += this.data.valueMap.get(val)+","
        }
      }else{
        tempVal=''
      }
      if(tempVal!=''){
        tempVal = tempVal.slice(0, -1);
      }
      this.data.formData[this.data.field['field']+this.data.betweenSign]=tempVal
      //调用父级，将值传出
      this.triggerEvent("change",{field:this.data.field['field']+this.data.betweenSign,val:tempVal})
      this.verify()
    },
    showPicker(){
      if(this.data.field['disabled']){
        this.setData({ isShow: false });
      }else{
        this.setData({ isShow: !this.data.isShow });
      }
    },
    onClose(){
      this.setData({ isShow: false });
    },

    onBlur(e){
      this.verify()
    },
    verify(){
      return formVerify(this)
    },
    noop() {},
  }
})
